import React, {FC, useState, useEffect} from 'react'
import {Upload, Modal, message} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import type {RcFile} from 'antd/es/upload'
import type {UploadFile} from 'antd/es/upload/interface'
import {useModel} from 'umi'
import {PageType} from '../constant'
import styles from './index.less'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'

interface ImageInfoType {
	fileList: any[]
	physicalFileList: any[]
	setFileList: (file: any) => void
	setPhysicalFileList: (file: any) => void
	pageType?: string
	detailRecord?: Record<string, string>
}

const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onload = () => resolve(reader.result as string)
		reader.onerror = (error) => reject(error)
	})

const imageInfo: FC<ImageInfoType> = ({
	fileList,
	setFileList,
	physicalFileList,
	setPhysicalFileList,
	pageType,
	detailRecord,
}) => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [previewOpen, setPreviewOpen] = useState(false)
	const [previewImage, setPreviewImage] = useState('')
	const [previewTitle, setPreviewTitle] = useState('')

	const handlePreview = async (file: UploadFile) => {
		const newFile = file
		if (!file.url && !file.preview) {
			newFile.preview = await getBase64(file.originFileObj as RcFile)
		}

		setPreviewImage(newFile.url || (newFile.preview as string))
		setPreviewOpen(true)
		setPreviewTitle(
			newFile.name ||
				newFile.url!.substring(newFile.url!.lastIndexOf('/') + 1),
		)
	}

	const handleChange = (info: any) => {
		setFileList(info.fileList)
	}

	const handlePhysicalChange = (info: any) => {
		setPhysicalFileList(info?.fileList)
	}

	// 获取图片路径
	const getImgsUrl = async (data: any) => {
		const crimeAuthImg = data.find((item: any) => item?.targetAttr === 1)
		if (crimeAuthImg) {
			setFileList([
				{
					uid: crimeAuthImg?.id,
					url: crimeAuthImg?.url,
					status: 'done',
					name: '无犯罪证明照片',
				},
			])
		}
		const physicalExaminationImg = data.find(
			(item: any) => item?.targetAttr === 2,
		)
		if (physicalExaminationImg) {
			setPhysicalFileList([
				{
					uid: physicalExaminationImg?.id,
					url: physicalExaminationImg?.url,
					status: 'done',
					name: '体检照片',
				},
			])
		}

		// if (urls.length === 0) return;
		// const data = await getPublicDownloadUrl(urls);
		// if (data.code === 0) {
		//   const [crimeAuthImg, physicalExaminationPhoto] = data.data;
		//   setFileList([{ url: crimeAuthImg.url }]);
		//   setPhysicalFileList([
		//     {
		//       url: physicalExaminationPhoto.url,
		//     },
		//   ]);
		// }
	}

	const beforeUpload = (file: any) => {
		const types = file.name.split('.')[1]
		const isPNG = [
			'png',
			'jpg',
			'bmp',
			'tif',
			'pcx',
			'tga',
			'exif',
			'fpx',
			'svg',
			'psd',
			'cdr',
			'dxf',
			'pcd',
			'ufo',
			'eps',
			'ai',
			'raw',
			'WMF',
			'webp',
			'avif',
			'apng',
		].includes(types)
		if (!isPNG) {
			message.error(
				` 仅支持bmp，jpg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，WMF，webp，avif，apng,格式`,
			)
		}
		return isPNG || Upload.LIST_IGNORE
	}

	useEffect(() => {
		if (pageType !== PageType.add && detailRecord) {
			// const urls = [];
			// if (detailRecord.crimeAuthImg) {
			//   urls.push(Number(detailRecord.noCrimePhoto));
			// }
			// if (detailRecord.physicalExaminationImg) {
			//   urls.push(Number(detailRecord.physicalExaminationPhoto));
			// }
			const urls: number[] = []
			if (detailRecord?.crimeAuthImg) {
				urls.push(Number(detailRecord?.crimeAuthImg))
			}
			if (detailRecord?.physicalExaminationImg) {
				urls.push(Number(detailRecord?.physicalExaminationImg))
			}
			if (urls?.length) {
				getPublicDownloadUrl(urls)
					.then((result: any) => {
						if (result?.success) {
							getImgsUrl(result?.data)
						}
					})
					.catch((err: any) => {
						message.error(err)
					})
			}
		}
	}, [detailRecord])

	return (
		<div className={styles.imageInfo}>
			<div className={styles.titleBox}>图片信息</div>
			<div style={{display: 'flex'}}>
				<div className={styles.imgBox}>
					<div className={styles.text}>无犯罪证明照片</div>
					<div className={styles.upload}>
						<Upload
							disabled={PageType.detail === pageType}
							action={uploadFileUrl}
							listType="picture-card"
							fileList={fileList}
							beforeUpload={beforeUpload}
							onPreview={handlePreview}
							onChange={handleChange}
							name={fileName}
							// onRemove={() => setFileList([])}
							data={{modelName: 'customer', targetAttr: '1'}}>
							{fileList.length >= 1 ? null : <PlusOutlined />}
						</Upload>
					</div>
				</div>
				<div className={styles.imgBox}>
					<div className={styles.text}>体检照片</div>
					<div className={styles.upload}>
						<Upload
							disabled={PageType.detail === pageType}
							action={uploadFileUrl}
							listType="picture-card"
							fileList={physicalFileList}
							beforeUpload={beforeUpload}
							onPreview={handlePreview}
							onChange={handlePhysicalChange}
							data={{modelName: 'customer', targetAttr: '2'}}
							name={fileName}>
							{physicalFileList.length >= 1 ? null : (
								<PlusOutlined />
							)}
						</Upload>
					</div>
				</div>
			</div>
			<Modal
				open={previewOpen}
				title={previewTitle}
				footer={null}
				onCancel={() => setPreviewOpen(false)}>
				<img alt="example" style={{width: '100%'}} src={previewImage} />
			</Modal>
		</div>
	)
}
export default imageInfo
